// @flow
import React from 'react'
import { Table, Button, notification } from 'antd'
import Time from 'react-time'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
// import { withRouter } from 'react-router'
import { Link } from 'react-router-dom'
import styles from './Home.css'

const columns = [
  { title: '序号',
    dataIndex: 'key',
    key: 'key'
  },
  { title: '作业编号',
    dataIndex: 'jobId',
    key: 'jobId',
    sorter: true
  },
  { title: '分析任务',
    dataIndex: 'taskName',
    key: 'taskName'
  },
  { title: '分析模型',
    dataIndex: 'projName',
    key: 'projName'
  },
  { title: '启动时间',
    dataIndex: 'startTime',
    key: 'startTime',
    render (text, b) {
      let now = new Date(parseInt(b.startTime))
      return <Time value={now} format='YYYY-MM-DD HH:mm:SS' />
    }
  },
  { title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    render (text, b) {
      if (b.endTime === '') {
        return ''
      } else {
        let now = new Date(parseInt(b.endTime))
        return <Time value={now} format='YYYY-MM-DD HH:mm:SS' />
      }
    }
  },
  { title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  { title: '运行状态',
    dataIndex: 'resultStatus',
    key: 'resultStatus'
  },
  { title: '运行结果',
    dataIndex: '',
    key: 'x',
    render (text, b) {
      let isDisabled = false
      if (b.hasApi === 'false') isDisabled = true
      return <div>
        <Button shape='circle' size={'default'} icon='file'
          onClick={() => componentFiles(b)} />&nbsp;&nbsp;
        <Link to={{ pathname: '/analysis/InterfaceData', query: { data:b } }}>
          <Button size={'default'} icon='book' disabled={isDisabled}>接口</Button>
        </Link>
      </div>
    }
  },
  { title: '模拟',
    dataIndex: '',
    key: 'y',
    render (text, b) {
      let isDisabled = false
      if (b.hasApi === 'false') isDisabled = true
      return <div>
        <Button size={'default'} disabled={isDisabled}
          onClick={() => sendMsg(b)}>模拟发送消息</Button>
      </div>
    }

  }
]

function componentFiles (b) {
  universalFetch(`${__SERVICE_API__}analysis/jobs/files?hdfsPath=` + b.hdfsPath,
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/jsoncharset=utf-8'
      }
    })
     .then((res) => res.json())
     .then((json) => {
       if (json.code !== 200000) {
         throw new Error(JSON.stringify({ code: json.code, message: json.message }))
       }
     })
     .catch((error) => {
       handleFetchError(error)
       console.error(error)
     })
}

function sendMsg (b) {
  notification['success']({
    message: '提醒',
    description: '正在推送消息...'
  })
  let url = `${__SERVICE_API__}analysis/jobs/` + b.jobId + '?status=' + b.resultStatus
  universalFetch(url,
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'Access-Control-Allow-Origin': '*'
      }
    })
     .then((res) => res.json())
     .then((json) => {
       if (json.code !== 200000) {
         throw new Error(JSON.stringify({ code: json.code, message: json.message }))
       }
       notification.open({
         message: '提醒',
         description: '消息推送成功!'
       })
     })
     .catch((error) => {
       handleFetchError(error)
       console.error(error)
     })
}

type State = {
  taskList: Array<Object>,
  pagination: Object,
  loading: boolean
}
class JobList extends React.Component {
  state: State
  constructor (props: Object) {
    super(props)
    this.state = {
      taskList:[],
      pagination: {},
      loading: false
    }
  }
  componentDidMount () {
    this.setState({ loading: true })
    universalFetch(`${__SERVICE_API__}analysis/jobs`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/jsoncharset=utf-8'
        }
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const pagination = { ...this.state.pagination }
        pagination.total = json.result.size
        this.setState({
          taskList:json.result.map((data, index) => {
            data['key'] = index
            return data
          }),
          pagination,
          loading: false
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    return (
      <div className={styles['main']}>
        <Table
          rowKey={(record) => record.key}
          dataSource={this.state.taskList}
          columns={columns}
          pagination={this.state.pagination}
          size='small' bordered
          loading={this.state.loading}
          title={() => ''}
          footer={() => '注:'}
        />
      </div>
    )
  }
}
export default JobList
